#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
线损导入和补偿功能演示
演示导入参考线线损文件的功能以及如何在校准中使用
"""

import json
import os

def demo_loss_import_and_compensation():
    """演示线损导入和补偿功能"""
    print("=" * 60)
    print("可调衰减器校准程序 - 线损导入和补偿功能演示")
    print("=" * 60)
    
    # 步骤1：演示导入线损文件
    print("\n1. 导入参考线线损文件")
    print("-" * 30)
    
    loss_file = "美国Meta 一根线 线损.json"
    if not os.path.exists(loss_file):
        print(f"❌ 错误：找不到线损文件 {loss_file}")
        return
    
    try:
        with open(loss_file, 'r', encoding='utf-8') as f:
            reference_loss_data = json.load(f)
        
        print(f"✅ 成功导入线损文件: {loss_file}")
        print(f"📊 线损数据点数: {len(reference_loss_data)}")
        print(f"📏 频率范围: {min(float(f) for f in reference_loss_data.keys()):.1f} - {max(float(f) for f in reference_loss_data.keys()):.1f} MHz")
        
        # 显示部分数据点
        print("\n📋 部分线损数据示例:")
        sample_freqs = [10.0, 100.0, 1000.0, 2000.0, 4000.0, 6000.0]
        for freq in sample_freqs:
            if str(freq) in reference_loss_data:
                loss = reference_loss_data[str(freq)]
                print(f"   频率: {freq:>6.1f} MHz  →  线损: {loss:>6.2f} dB")
        
    except Exception as e:
        print(f"❌ 导入失败: {str(e)}")
        return
    
    # 步骤2：演示线损查找功能
    print("\n2. 线损查找功能测试")
    print("-" * 30)
    
    def get_reference_loss(frequency):
        """获取指定频率的参考线线损"""
        try:
            freq_str = str(float(frequency))
            
            # 直接查找
            if freq_str in reference_loss_data:
                return float(reference_loss_data[freq_str])
            
            # 查找最接近的频率点
            frequencies = [float(f) for f in reference_loss_data.keys()]
            closest_freq = min(frequencies, key=lambda x: abs(x - float(frequency)))
            
            return float(reference_loss_data[str(closest_freq)])
            
        except Exception:
            return 0.0
    
    test_frequencies = [50.0, 150.0, 999.0, 2500.0, 5000.0, 6500.0]
    print("🔍 测试查找各频率点的线损:")
    
    for freq in test_frequencies:
        loss = get_reference_loss(freq)
        print(f"   频率: {freq:>6.1f} MHz  →  线损: {loss:>6.2f} dB")
    
    # 步骤3：演示校准结果补偿
    print("\n3. 校准结果补偿演示")
    print("-" * 30)
    
    # 模拟校准测量数据
    simulated_calibration_data = [
        {"freq": 100.0, "attenuation": 10.0, "measured_power": -25.3},
        {"freq": 1000.0, "attenuation": 20.0, "measured_power": -32.8},
        {"freq": 2000.0, "attenuation": 30.0, "measured_power": -45.1},
        {"freq": 4000.0, "attenuation": 40.0, "measured_power": -52.7},
        {"freq": 6000.0, "attenuation": 50.0, "measured_power": -63.2},
    ]
    
    print("📐 校准数据补偿计算:")
    print("   (模拟校准过程中减去参考线线损)")
    print()
    
    for data in simulated_calibration_data:
        freq = data["freq"]
        att = data["attenuation"]
        measured = data["measured_power"]
        
        # 获取参考线线损
        ref_loss = get_reference_loss(freq)
        
        # 计算补偿后的值 (线损为负值，减去线损相当于补偿)
        compensated = measured - ref_loss
        
        print(f"   📍 频率: {freq:>6.1f} MHz, 衰减: {att:>4.1f} dB")
        print(f"      原始测量值: {measured:>7.2f} dBm")
        print(f"      参考线线损: {ref_loss:>7.2f} dB")
        print(f"      补偿后数值: {compensated:>7.2f} dBm")
        print(f"      补偿量:     {-ref_loss:>7.2f} dB")
        print()
    
    # 步骤4：说明使用方法
    print("4. 使用说明")
    print("-" * 30)
    print("🎯 在校准程序中使用此功能的步骤:")
    print("   1. 点击 '导入参考线线损文件' 按钮")
    print("   2. 选择线损JSON文件 (如: 美国Meta 一根线 线损.json)")
    print("   3. 确认导入成功后，开始校准")
    print("   4. 校准过程中会自动：")
    print("      - 根据频率查找对应的线损值")
    print("      - 从测量结果中减去参考线线损")
    print("      - 得到补偿后的校准数据")
    print("   5. 最终校准结果已经考虑了线损补偿")
    
    print("\n📊 线损补偿的意义:")
    print("   - 消除参考线缆本身的损耗影响")
    print("   - 提高校准精度")
    print("   - 得到衰减器的真实衰减特性")
    
    print("\n✅ 线损导入和补偿功能演示完成!")
    print("=" * 60)

if __name__ == "__main__":
    demo_loss_import_and_compensation()